package com.ruoyi.common.mybatisplus.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.binding.MapperMethod;

import java.util.Collection;
import java.util.function.Function;

/** 对批量新增进行优化
 * @author zgx *
 * @date 2022年11月17日 15:29
 */
public class BatchServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M,T> {

    /**
     * 默认最大更新条数
     */
    private static int DEFAULT_BATCH_SIZE = 500;




    /**注意: 批量更新无法更新版本号
     *
     * 批量更新基础类
     * @param entityList 更新实体
     * @param queryWrapper 根据条件逐条更新
     * @return 返回是否更新成功 true:成功 false 失败
     */
    public boolean updateBatchByQueryWrapper(Collection<T> entityList, Function<T, QueryWrapper> queryWrapper) {
        return updateBatchByQueryWrapper(entityList,DEFAULT_BATCH_SIZE,queryWrapper);
    }

    public boolean updateBatchByQueryWrapper(Collection<T> entityList, int batchSize, Function<T, QueryWrapper> queryWrapper) {
        String sqlStatement = getSqlStatement(SqlMethod.UPDATE);
        return executeBatch(entityList, batchSize, (sqlSession, entity) -> {
            MapperMethod.ParamMap param = new MapperMethod.ParamMap();
            param.put(Constants.ENTITY, entity);
            param.put(Constants.WRAPPER, queryWrapper.apply(entity));
            sqlSession.update(sqlStatement, param);
        });
    }


}